<?php
require_once 'dao/AbstractDAO.php';

class SequenceDAO extends AbstractDAO{
	private static $TABLE = "SEQUENCE";
	private function insertSequence($sequencePrefix, $sequenceNum){
		$values = array();
		$values["SEQUENCE_PREFIX"] = $sequencePrefix;
		$values["SEQUENCE_NUM"] = $sequenceNum;
		
		return $this->insert(SequenceDAO::$TABLE, $values);
	}
	
	private function selectMaxSequence($sequencePrefix){
		$result = $this->selectOne(SequenceDAO::$TABLE, "MAX(SEQUENCE_NUM) MAX_SEQUENCE_NUM", "SEQUENCE_PREFIX = '$sequencePrefix'");
		if ($result != null)
			return $result["MAX_SEQUENCE_NUM"];
		else 
			return 0;
	}
	
	public function createNewId($sequencePrefix, $sequenceLength = 4, $retryCount = 3){
		$maxSequenceNum = $this->selectMaxSequence($sequencePrefix);
		$insertSuccess = false;
		$sequenceNum = -1;
		for ($i = 0; $i < $retryCount ; $i++){
			$sequenceNum = $maxSequenceNum + 1 + $i;
			try{
				$this->insertSequence($sequencePrefix, $sequenceNum);
				$this->commit();
				$insertSuccess = true;
				break;
			}
			catch(Exception $e){
				Logger::debug("createNewId prefix[$sequencePrefix] retry count ".($i + 1));
			}
		}
		if ($insertSuccess)
			return $sequencePrefix.str_pad("$sequenceNum", $sequenceLength, "0", STR_PAD_LEFT);
		else
			throw new Exception("ID creation was failed. sequencePrefix[$sequencePrefix]");
	}
}
?>